package com.xtjc03.serial.handler;

import com.xtjc03.jms.service.JmsServiceImpl;
import com.xtjc03.serial.domain.ComProperties;
import org.apache.mina.core.service.IoHandlerAdapter;
import org.apache.mina.core.session.IoSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


@Component
public class ComMsgHandler extends IoHandlerAdapter {

    private static final Logger logger = LoggerFactory.getLogger(ComMsgHandler.class);

    private static JmsServiceImpl jmsService;

    private static ComProperties comProperties;

    @Resource
    private void setSerialService(JmsServiceImpl jmsService) {
        ComMsgHandler.jmsService = jmsService;
    }

    @Resource
    private void setComProperties(ComProperties comProperties) {
        ComMsgHandler.comProperties = comProperties;
    }

    @Override
    public void messageReceived(IoSession session, Object message) throws Exception {
        if (message instanceof String){
            String msg = (String) message;
            logger.info("[Debug]:Receiver<- {}", msg);
            if (msg.startsWith("xtjc03led")){
                jmsService.addSender("xtjc03led", msg);
            }else if (msg.startsWith("xtjc03beep")){
                jmsService.addSender("xtjc03beep", msg);
            }else if (msg.startsWith("xtjc03temp")){
                jmsService.addSender("xtjc03temp", msg);
            }

        }
    }

    @Override
    public void messageSent(IoSession session, Object message) throws Exception {
        if (message instanceof String){
            String msg = (String) message;
            logger.info("[Debug]:Send-> {}", msg);
        }
    }

    @Override
    public void exceptionCaught(IoSession session, Throwable cause) throws Exception {
        super.exceptionCaught(session, cause);
    }

    @Override
    public void sessionCreated(IoSession session) throws Exception {
        session.write("你好\r\n");
    }
}
